/************************************************************************/
/* Game                                                                 */
/************************************************************************/
#include "Game/Animations/AnimationSet.h"

//Cross include for destruction
#include "Game/Animations/StandardAnimationSet.h"

namespace TD_Game {

	/************************************************************************/
	/* Private functions                                                    */
	/************************************************************************/
	Animation * AnimationSet::getAnimation(const string &animName) const {
		Animation *pAnim = NULL;
		map<string, Animation *>::const_iterator iter = m_animationMap.find(animName);
		if (iter == m_animationMap.end()) return NULL;
		if (iter->first.size() > 0) {
			pAnim = dynamic_cast<Animation *>(iter->second);
		}
		return(pAnim);
	}

	/************************************************************************/
	/* ctors and dtors                                                      */
	/************************************************************************/
	AnimationSet::AnimationSet() {
		m_pCurrAnimation = NULL;
		m_currAnimationName = "_NO_ANIMATION_";
	}

	AnimationSet::AnimationSet(const AnimationSet &rhs) {
		m_pCurrAnimation = rhs.getCurrentAnimation();
		m_pSprites = rhs.getSprites();
		m_currAnimationName = rhs.getCurrentAnimationName();
	}

	AnimationSet & AnimationSet::operator =(const AnimationSet &rhs) {
		m_pCurrAnimation = rhs.getCurrentAnimation();
		m_pSprites = rhs.getSprites();
		m_currAnimationName = rhs.getCurrentAnimationName();
		return(*this);
	}

	AnimationSet::AnimationSet(const string &startingAnimation) {
		m_currAnimationName = startingAnimation;

		m_pCurrAnimation = NULL;
	}

	AnimationSet::~AnimationSet() {
		map<string, Animation *>::iterator iter = m_animationMap.begin();
		map<unsigned int, bool> auxiliaryMap;
		map<unsigned int, bool>::iterator auxiliaryIter;

		while ( iter != m_animationMap.end()) {
			if(iter->second->getCurrentTile() != NULL) {
				if(auxiliaryMap.find((unsigned int) iter->second) == auxiliaryMap.end()) {
					auxiliaryMap[(unsigned int) iter->second] = true;
					delete iter->second;
				}
				m_animationMap.erase( iter++ );

			} else {
				++iter;
			}
		}
	}

	/************************************************************************/
	/* Functionalities                                                      */
	/************************************************************************/



	void AnimationSet::render(SDL_Surface *const g_destSurface, unsigned int deltaTime, const Coord2D &offsetPos) {
		Animation *pAnim = getAnimation(m_currAnimationName);
		if(pAnim != NULL) {
			pAnim->setPosition(offsetPos);
			pAnim->render(g_destSurface, deltaTime);
		}
	}



}